<?php

namespace app\admin\controller;

use app\admin\model\OilOrder as OilOrderModel;
use app\admin\model\UserMoneyLog;
use app\admin\model\Wechat;
use app\admin\model\Alipay;
use app\common\controller\Backend;
use think\db\exception\PDOException;
use think\exception\ValidateException;
use think\facade\Db;

/**
 * 加油退款
 *
 */
class OilOrderRefund extends Backend
{
    /**
     * OilOrderRefund模型对象
     * @var \app\admin\model\OilOrderRefund
     */
    protected $model = null;

    protected $quickSearchField = ['id'];

    protected $withJoinTable = ['oilOrderInfo'];

    protected $defaultSortField = 'id,desc';

    protected $preExcludeFields = ['createtime', 'updatetime'];

    public function initialize()
    {
        parent::initialize();
        $this->model = new \app\admin\model\OilOrderRefund;
    }

    /**
     * 查看
     */
    public function index()
    {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->param('select')) {
            $this->select();
        }

        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->field($this->indexField)
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->order($order)
            ->paginate($limit);

        $this->success('', [
            'list' => $res->items(),
            'total' => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }

    /**
     * 编辑
     */
    public function edit()
    {
        $id = $this->request->param($this->model->getPk());
        $row = $this->model->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
            $this->error(__('You have no permission'));
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data = $this->excludeFields($data);
            $result = false;
            Db::startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('edit');
                        $validate->check($data);
                    }
                }
                if ($data['state']) {
                    if ($row['state'] == 1) {
                        throw new ValidateException('请勿重复退款');
                    }
                    // 退款逻辑
                    $order = OilOrderModel::where('id', $data['order_id'])->field('pay_type, pay_price,order_sn')->find();
                    if ($order['pay_type'] == 'wechat') {
                        $wechat = new Wechat();
                        $result = $wechat->getPayment()->refund->byOutTradeNumber($order['order_sn'], $data['refund_sn'], 1, $data['price'] * 100, [
                            // 可在此处传入其他参数，详细参数见微信支付文档
                            'refund_desc' => '加油退款',
                        ]);
                        if (isset($result['return_code']) && $result['return_code'] == 'FAIL') {
                            throw new ValidateException($result['return_msg']);
                        }
                        if (isset($result['result_code']) && $result['result_code'] == 'FAIL') {
                            throw new ValidateException($result['err_code_des']);
                        }
                        $data['refund_id'] = $result['refund_id'];
                    } elseif ($order['pay_type'] == 'balance') {
                        UserMoneyLog::create([
                            'user_id' => $order['user_id'],
                            'memo' => '加油退款',
                            'money' => $data['price']
                        ]);
                    } elseif ($order['pay_type'] == 'alipay') {
                        $alipay = new Alipay();
                        $alipay->refund($order->order_sn, $data['price']);
                    }
                }
                $result = $row->save($data);
                Db::commit();
            } catch (ValidateException|PDOException|\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Update successful'));
            } else {
                $this->error(__('No rows updated'));
            }

        }

        $this->success('', [
            'row' => $row
        ]);
    }

}